package com.hancher.gamelife2.encrypt;

import android.content.res.AssetManager;
import android.os.Bundle;

import com.hancher.common.androidutil.ClipboardUtil;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.base.BaseApplication;
import com.hancher.common.base.BaseMvpFragment;
import com.hancher.common.javautil.Base64Util;
import com.hancher.common.javautil.DecryptUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.javautil.Md5Util;
import com.hancher.common.javautil.Sha256Util;
import com.hancher.gamelife2.databinding.FragmentEncryptBinding;
import com.hancher.gamelife2.home.HomePresenter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 描述 : 加密 <br/>
 * 时间 : 2024/5/21 14:46 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class EncryptFragment extends BaseMvpFragment<FragmentEncryptBinding, HomePresenter> {

    HashMap<String, String> map = new HashMap<>();
    HashMap<String, String> mapRevert = new HashMap<>();
    private String MORSE_CSV = "morse/摩斯电码表.csv";
    private Disposable d;

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    protected void initListener() {
        binding.tvEncryptType.setOnClickListener(v -> {
            new XPopup.Builder(getContext())
                    .atView(binding.tvEncryptType)
                    .popupPosition(PopupPosition.Bottom)
                    .hasShadowBg(false)
                    .animationDuration(0)
                    .asAttachList(new String[]{"hancher1", "hancher2", "摩斯电码", "base64", "md5", "sha256"},
                            new int[]{},
                            (position, text) -> binding.tvEncryptType.setText(text))
                    .show();
        });
        binding.btnPaste.setOnClickListener(v -> {
            binding.editIn.setText(ClipboardUtil.paste());
        });
        binding.btnCopy.setOnClickListener(v -> {
            ClipboardUtil.copy(binding.editOut.getText().toString());
        });
        binding.tvEncrypt.setOnClickListener(v -> {
            String textIn = binding.editIn.getText().toString();
            String textSalt = binding.etSalt.getText().toString();
            String textPsd = binding.etPsd.getText().toString();
            String textOut = "";
            String textType = binding.tvEncryptType.getText().toString();
            try {
                if ("hancher1".equals(textType)) {
                    textOut = DecryptUtil.encrypt(textIn);
                } else if ("hancher2".equals(textType)) {
                    textOut = DecryptUtil.encrypt2(textIn);
                } else if ("摩斯电码".equals(textType)) {
                    char[] chars = textIn.toUpperCase().toCharArray();
                    String[] newChars = new String[chars.length];
                    for (int i = 0; i < chars.length; i++) {
                        newChars[i] = map.get(String.valueOf(chars[i]));
                        if (newChars[i] == null) {
                            newChars[i] = String.valueOf(chars[i]);
                        } else {
                            LogUtil.i("转换成功 %s->%s", String.valueOf(chars[i]), newChars[i]);
                        }
                    }
                    StringBuffer sb = new StringBuffer();
                    for (String newChar : newChars) {
                        if (sb.length() != 0) {
                            sb.append("/");
                        }
                        sb.append(newChar);
                    }
                    textOut = sb.toString();
                } else if ("base64".equals(textType)) {
                    textOut = Base64Util.encode(textIn);
                } else if ("md5".equals(textType)) {
                    if (EmptyUtil.isNotEmpty(textSalt)) {
                        textOut = Md5Util.getStrMd5OnSlat(textIn, textSalt);
                    } else {
                        textOut = Md5Util.getStrMd5(textIn);
                    }
                } else if ("sha256".equals(textType)) {
                    if (EmptyUtil.isNotEmpty(textSalt)) {
                        textOut = Sha256Util.hmacSHA256(textIn, textSalt);
                    } else {
                        textOut = Sha256Util.getSHA256Str(textIn);
                    }
                }

            } catch (Exception e) {
                textOut = e.getMessage();
            }
            binding.editOut.setText(textOut);
        });
        binding.tvDecrypt.setOnClickListener(v -> {
            String textIn = binding.editIn.getText().toString();
            String textSalt = binding.etSalt.getText().toString();
            String textPsd = binding.etPsd.getText().toString();
            String textOut = "";
            String textType = binding.tvEncryptType.getText().toString();
            try {
                if ("hancher1".equals(textType)) {
                    textOut = DecryptUtil.decrypt(textIn);
                } else if ("hancher2".equals(textType)) {
                    textOut = DecryptUtil.decrypt2(textIn);
                } else if ("摩斯电码".equals(textType)) {
                    String spl = textIn.replace(".", "").replace("-", "");
                    if (spl.length() > 0) {
                        spl = String.valueOf(spl.charAt(0));
                    }
                    String[] chars = textIn.split(spl);
                    String[] newChars = new String[chars.length];
                    for (int i = 0; i < chars.length; i++) {
                        newChars[i] = mapRevert.get(chars[i]);
                        if (newChars[i] == null) {
                            newChars[i] = chars[i];
                        } else {
                            LogUtil.i("转换成功 %s->%s", chars[i], newChars[i]);
                        }
                    }
                    StringBuffer sb = new StringBuffer();
                    for (String newChar : newChars) {
                        sb.append(newChar);
                    }
                    textOut = sb.toString();
                } else if ("base64".equals(textType)) {
                    textOut = Base64Util.decode(textIn);
                } else if ("md5".equals(textType)) {
                    textOut = "暂不支持";
                } else if ("sha256".equals(textType)) {
                    textOut = "暂不支持";
                }

            } catch (Exception e) {
                textOut = e.getMessage();
            }
            binding.editOut.setText(textOut);
        });
    }

    @Override
    protected void initData() {
        try {
            readCsv();
        } catch (IOException e) {
            LogUtil.e("err:", e);
        }
        LogUtil.map2Json("csv:" + map);
    }

    private void readCsv() throws IOException {
        map.clear();
        AssetManager assetManager = BaseApplication.getInstance().getAssets();
        InputStream in = assetManager.open(MORSE_CSV);
        InputStreamReader isr1 = new InputStreamReader(in);
        BufferedReader isr = new BufferedReader(isr1);

        String[] line;
        isr.readLine();
        String strLine;
        while (true) {
            strLine = isr.readLine();
            if (EmptyUtil.isEmpty(strLine)) {
                break;
            }
            line = strLine.split(",");
            if (line.length == 2) {
                map.put(line[0], line[1]);
                mapRevert.put(line[1], line[0]);
            }
        }
        isr.close();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

}